export async function uploadFile(file: File): Promise<string> {
    const url = 'http://localhost:5275/api/FileUpload/upload'
    const fd = new FormData()
    fd.append('file', file)
    const res = await fetch(url, { method: 'POST', body: fd })
    const text = await res.text()
    let json: any
    try { json = JSON.parse(text) } catch { json = { code: res.status, message: text, raw: text } }
    if (!res.ok) {
        // throw error with server message if available
        const msg = json?.message || `upload failed (status ${res.status})`
        throw new Error(msg)
    }
    const fileUrl = json.data?.fileUrl ?? json.data?.url ?? json.fileUrl ?? json.url ?? json.data?.path ?? json.path
    if (fileUrl) return String(fileUrl)
    if (json.data && typeof json.data === 'string') return json.data
    return ''
}

export function uploadFileWithProgress(file: File, onProgress?: (percent: number) => void): Promise<string> {
    const url = 'http://localhost:5275/api/FileUpload/upload'
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        const fd = new FormData()
        fd.append('file', file)
        xhr.open('POST', url, true)
        xhr.upload.onprogress = (ev) => {
            if (ev.lengthComputable && onProgress) {
                const pct = Math.round((ev.loaded / ev.total) * 100)
                try { onProgress(pct) } catch (e) { /* ignore */ }
            }
        }
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                const text = xhr.responseText
                let json: any
                try { json = JSON.parse(text) } catch { json = { code: xhr.status, message: text, raw: text } }
                if (xhr.status >= 200 && xhr.status < 300) {
                    const fileUrl = json.data?.fileUrl ?? json.data?.url ?? json.fileUrl ?? json.url ?? json.data?.path ?? json.path
                    if (fileUrl) return resolve(String(fileUrl))
                    if (json.data && typeof json.data === 'string') return resolve(json.data)
                    return resolve('')
                }
                const msg = json?.message || `upload failed (status ${xhr.status})`
                return reject(new Error(msg))
            }
        }
        xhr.onerror = () => reject(new Error('network error'))
        xhr.send(fd)
    })
}


